<template>
  <div class="login-container">
    <el-card class="login-box">
      <h1 class="login-title">欢迎登录</h1>
      <el-form
        :model="form"
        @submit.prevent="handleLogin"
        label-position="top"
        ref="loginFormRef"
      >
        <el-form-item label="用户名">
          <el-input
            v-model="form.username"
            placeholder="请输入用户名"
            :prefix-icon="EditPen"
          />
        </el-form-item>
        <el-form-item label="密码">
          <el-input
            v-model="form.password"
            type="password"
            show-password
            placeholder="请输入密码"
            :prefix-icon="Lock"
          />
        </el-form-item>
        <el-button
          type="primary"
          native-type="submit"
          class="login-button"
        >
          登录
        </el-button>
        <el-alert
          v-if="errorMessage"
          :title="errorMessage"
          type="error"
          show-icon
          class="error-message"
        />
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { login } from '../api/auth';
import { EditPen, Lock } from '@element-plus/icons-vue';

const router = useRouter();

// 响应式表单数据
const form = ref({
  username: '',
  password: '',
});

const rememberMe = ref(false);
const loading = ref(false);
const errorMessage = ref('');
const loginFormRef = ref(null); // 表单引用

// 表单验证规则（如果需要）
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
};

// 处理登录逻辑
const handleLogin = () => {
  // 模拟验证逻辑（实际使用时请替换为真实验证）
  if (!form.value.username || !form.value.password) {
    errorMessage.value = '用户名或密码不能为空';
    return;
  }

  loading.value = true;
  errorMessage.value = '';

  // 调用登录 API
  login(form.value.username, form.value.password)
    .then((user) => {
      localStorage.setItem('isAuthenticated', 'true');
      localStorage.setItem('user', JSON.stringify(user));
      localStorage.setItem('token', user.token);

      ElMessage.success('登录成功');
      router.push({path: '/'});
    })
    .catch((error) => {
      ElMessage.error(error.message);
    })
    .finally(() => {
      loading.value = false;
    });
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: #263445;
}
.login-box {
  width: 400px;
  padding: 20px;
  border-radius: 12px;
}
.login-title {
  color: var(--el-color-primary);
  text-align: center;
  margin-bottom: 24px;
}
.login-button {
  width: 100%;
  margin-top: 10px;
}
.error-message {
  margin-top: 15px;
}
</style>